package org.zlb.netty.client.rpc;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.atomic.AtomicInteger;

import org.zlb.netty.dbo.RpcRequest;
import org.zlb.netty.dbo.RpcResponse;

public class RpcMessageClientProxy<T> implements InvocationHandler {

    private RpcMessageClient rpcClient;
    private  Class<T> serviceInterface;
    private int i;
    
    public RpcMessageClientProxy(Class<T> serviceInterface, RpcMessageClient rpcClient, int i) {
        this.serviceInterface = serviceInterface;
        this.rpcClient = rpcClient;
        this.i = i;
    }

    @SuppressWarnings("unchecked")
    public T getClientIntance(){
        return (T) Proxy.newProxyInstance(serviceInterface.getClassLoader(), new Class<?>[]{serviceInterface}, this);
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        RpcRequest req = new RpcRequest();
        req.setRequestId(String.valueOf(i));
        req.setClassName(serviceInterface.getName());
        req.setMethodName(method.getName());
        req.setParamTypes(method.getParameterTypes());
        req.setArguments(args);
        
        RpcResponse resp = rpcClient.sendRequest(req);
        return resp.getResult();
    }
    
    public static void main(String[] args) {
        RpcMessageClient client = new RpcMessageClient("127.0.0.1", 8088);
        RpcMessageClientThread task = new RpcMessageClientThread(client);
        new Thread(task).start();
        
        long time1 = System.currentTimeMillis();
        System.out.println();
        AtomicInteger id = new AtomicInteger(0);
        for (int i=0; i<10000; i++) {
            RpcMessageClientProxy<?> clientProxy = new RpcMessageClientProxy<>(IHello.class, client, id.getAndIncrement());
            IHello hello = (IHello) clientProxy.getClientIntance ();
            String s = hello.say ( "socket rpc " + i );
            System.out.println(s);
        }
        
        for (int i=0; i<10000; i++) {
            RpcMessageClientProxy<?> clientProxy = new RpcMessageClientProxy<>(ICacl.class, client, id.getAndIncrement());
            ICacl calc = (ICacl) clientProxy.getClientIntance ();
            int s = calc.add(i, 1+2);
            System.out.println(s);
        }
        
        long time2 = System.currentTimeMillis();
        long time = (time2 - time1)/1000;
        System.out.println("共耗时：" + time);
    }

}
